<?php
namespace app\api\service\provider;
/**
 * UserProvider
 * @Author Vee7
 * @Date 2021/12/23
 * @Time 15:01
 * @Description Vee7
 */

use app\api\service\serv\ClientService;
use app\admin\model\Client;
use think\facade\Cache;


class ClientProvider implements ClientService
{
    protected $client_cache_key_pre;

    public function __construct(){
        $this->client_cache_key_pre = 'client_info_';
    }

    /***
     * @return string
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 21:12
     * @Description 接口签名校验
     */
    public function checkSign($sign,$randomstr,$client_uname)
    {
        //从缓存获取应用授权秘钥（有条件使用Redis会更好）
        $client_user = Cache::get($this->client_cache_key_pre.$client_uname);
        //如果缓存不存在，则查询数据库并缓存
        if(!$client_user){
            $client_model = Client::where('client_uname',$client_uname)->find();
            if(!$client_model){
                return false;
            }
            $client_user = $client_model->toArray();
            if($client_user['status'] == 0){
                return false;
            }
            //生成应用授权缓存，避免每次访问页面都查询数据库，但记得修改应用授权信息时需要清除该应用的缓存
            Cache::set($this->client_cache_key_pre.$client_uname,$client_user,3600*24*30);
        }

        $client_scret = $client_user['client_scret'];
        //根据加密规则（与前台规则一致）计算签名
        //规则：
        //1.字符串连接 秘钥+当前年-月-日-时-分+前台的随机字符串
        //2.三次md5加密字符串
        //3.加密后转为全大写
        //得到签名
        $time = date('Y-m-d-H-i',time());
        $str = $client_scret.$time.$randomstr;
        $once = md5($str);
        $twice = md5($once);
        $sign = md5($twice);
        return strtoupper($sign);
    }

}